import React from 'react';
import ReactDOM from 'react-dom';
import { inject, observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import * as mobx from 'mobx';
import {WeaErrorPage, WeaHelpfulTip, WeaTools} from 'ecCom';
import { Button, Modal, message } from 'antd';
import WfForward from '../../asyncComps/Forward';
import allStore from '../../stores';
import { WeaTop, WeaRightMenu, WeaTab, WeaLeftRightLayout, WeaShare, WeaBrowser,WeaLeftTree, WeaPopoverHrm, WeaLocaleProvider, WeaDropdown } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const { ButtonSelect } = WeaDropdown;
//自定义组件
import Condition from './Condition';
import TagTypeSelectDialog from "../../asyncComps/TagTypeSelectDialog";
import {toJS} from "mobx";
@inject('attentionStore')

@observer
class Attention extends React.Component {

  constructor(props) {
    super(props);
    this.doInit(this.props);
    this.state = {
      visible:false,
      msgList:[],
      shareParams:{}
    }
  }
  doInit(props) {
    const { location, attentionStore } = props;
    attentionStore.init(location.query || {});
    _ListenerCtrl.bind();
  }
  componentDidMount() {
    // const { hover } = this.props.attentionStore;
    this.timerID=setTimeout(()=>{ 
      $(".wf_attention_div_btn").on("mouseover mouseout",function(event){
          const str = $(this).attr('id').substr($(this).attr('id').indexOf('_'))
          if(event.type == "mouseover"){  
           jQuery("#attentionSpan"+str).css("display","block")
          }else if(event.type == "mouseout"){
           jQuery("#attentionSpan"+str).css("display","none")
          }
         })
   },1000)
  }
  componentDidUpdate(){
    // const { hover } = this.props.attentionStore;
    this.timerID=setTimeout(()=>{ 
      $(".wf_attention_div_btn").on("mouseover mouseout",function(event){
          const str = $(this).attr('id').substr($(this).attr('id').indexOf('_'))
          if(event.type == "mouseover"){  
           jQuery("#attentionSpan"+str).css("display","block")
          }else if(event.type == "mouseout"){
           jQuery("#attentionSpan"+str).css("display","none")
          }
         })
   },1000)
  }
  componentWillUnmount() {
    const { attentionStore } = this.props;
    attentionStore.clearStatus();
    _ListenerCtrl.bind();
    clearTimeout(this.timerID);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      const { attentionStore } = this.props;
      attentionStore.clearStatus();
      this.doInit(nextProps);
    }
  }

  setShowSearchAd=bool => { this.props.attentionStore.setShowSearchAd(bool) }
  hideSearchAd=() => this.props.attentionStore.setShowSearchAd(false);
  onSearch= v => { this.props.attentionStore.getSessionkey() };
  render() {
    const { attentionStore, location = {} } = this.props;
    const { loading, title, showSearchAd, form, tableStore, topTab, tabKey, smsVisible, smsParams, showBatchSubmit, emailVisible, fwquery } = attentionStore;
    const formParams = form.getFormParams() || {};
    const loadingTable = tableStore.loading;
    // console.log(tableStore)
    return (
      <div style={{ height: "100%", width: "100%" }} className='wf-pc4mobx-supervise'>
        <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@fap3xc`} />
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@903lyb`} datas={this.getRightMenu()} collectParams={{ favname: title, favouritetype: '2', importantlevel: '1' }}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@nfzme4`}
            title={title}
            loading={loading || loadingTable}
            icon={<i className='icon-coms-workflow' />}
            iconBgcolor='#0079DE'
            buttons={this.getbtns()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
          >
            <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@ost43n`}
              leftCom={this.getTree()}
            >
              <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@05dk9o`}
                leftStyle={{paddingRight:300}}
                className={'attention_tab_limit'}
                needCalLsPaddingRight={true}
                datas={topTab}
                keyParam={'groupid'}
                selectedKey={tabKey}
                onChange={this.changeTab}
                buttonsAd={this.getTabButtonsAd()}
                searchType={['base', 'advanced']}
                setShowSearchAd={this.setShowSearchAd}
                hideSearchAd={this.hideSearchAd}
                showSearchAd={showSearchAd}
                searchsBaseValue={formParams.requestname}
                searchsAd={
                  <Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@v5pnxb`} queryStore={attentionStore} />
                }
                onSearch={this.onSearch}
                onSearchChange={v => { attentionStore.appendFormFields({ requestname: v }) }}
              />
              <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@kkl2fw`}
                comsWeaTableStore={tableStore}
                hasOrder={true}
                needScroll={true}
                register_table={attentionStore.reLoad}
                getColumns={this.getColumns}
              />
            </WeaLeftRightLayout>
          </WeaTop>
        </WeaRightMenu>
        <TagTypeSelectDialog ecId={`${this && this.props && this.props.ecId || ''}_TagTypeSelectDialog@dgqe6i`} curStore={allStore.wfFollowTypeSettingStore} refreshTabs={attentionStore.getTree} refresh={attentionStore.getSessionkey} reloadway={"1"}/>
        <WfForward ecId={`${this && this.props && this.props.ecId || ''}_WfForward@pwg5ni`} />
        {
          // <WeaShare
          //   visible={this.state.visible}
          //   onVisilbeChange={bool => this.setState({visible:bool})}
          //   shareParams={this.state.shareParams}
          //   msginfo={this.state.msgList}
          // />
        }
      </div>
    )
  }

  //tab切换
  changeTab = (tabKey) => {
    const { attentionStore } = this.props;
    attentionStore.tabKey = tabKey;
    attentionStore.getSessionkey();
  }

    getColumns = (columns) => {
        const columnsJS = toJS(columns);
        columnsJS.forEach(col => {
            if(col.dataIndex === "unoperators"){
                const title = (
                    <span>
                        <span title={col.title}>
                            { col.title }
                        </span>
                        {<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@cgz7hg@${col.dataIndex}`} style={{ marginLeft: 5 }} title={getLabel(516719,"可在【个性化设置】中设置未操作者的显示类型")} placement="top" />}
                    </span>
            )
                col.title = title;
            }
        });
        return columnsJS;
    }

    search = () => { this.props.attentionStore.getSessionkey(); this.props.attentionStore.setShowSearchAd(false); }
    reset = () => { this.props.attentionStore.clearFormFields();}
    cancel = () => { this.props.attentionStore.setShowSearchAd(); }
  //搜索框底部按钮
  getTabButtonsAd() {
    const { attentionStore } = this.props;
    return [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kz2li8@search`} type="primary" onClick={this.search}>{getLabel(197, '搜索')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@uy4roh@reset`} type="ghost" onClick={this.reset}>{getLabel(2022, '重置')}</Button>),
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@elsv0f@cancel`} type="ghost" onClick={this.cancel}>{getLabel(31129, '取消')}</Button>)
    ];
  }
  onSearchLabelClick = () => {
    const { attentionStore } = this.props.
      attentionStore.setShowSearchAd(false);
      attentionStore.setSelectedTreeKey("");
      attentionStore.clearFormFields();
      // attentionStore.getSessionkey();
      attentionStore.onSearchLabelClick();
  }

  onSelect = (key, counts, types) => {
    const { attentionStore } = this.props;
    attentionStore.setShowSearchAd(false);
    attentionStore.setSelectedTreeKey(key);
    attentionStore.setByTree(key, counts, types);
  }
  //左侧树
  getTree() {
    const { attentionStore } = this.props;
    const { leftTree, leftTreeCountType, leftTreeCount, forceRender, selectedTreeKey } = attentionStore;
    return (
      <WeaLeftTree ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@f098ol`}
        forceRender={forceRender}
        datas={mobx.toJS(leftTree)}
        countsType={leftTreeCountType}
        // counts={mobx.toJS(leftTreeCount)}
        selectedKeys={[selectedTreeKey]}
        onSearchLabelClick={this.onSearchLabelClick}
        onSelect={this.onSelect}
      />
    )
  }


  typeSetting = () => {
    window.followTypeSettingStore.showDialog = true ;
    window.followTypeSettingStore.openType = "bqsz" ;
  }
  batchAttention = () => {this.doAttention() };
  getbtns() {
    const { attentionStore } = this.props;
    const { tableStore } = attentionStore;
    const selectedRowKeys = tableStore.selectedRowKeys;
    let btns = [];
    const datas = [
      { key: 'batchAttention', show: getLabel(503955, '批量关注'), selected: true },
      // { key: 'batchForward', show: '转发' },
    ];
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@71re5b@followTypeSetting`} type="primary" onClick={this.typeSetting}>{getLabel(503952, '关注类型设置')}</Button>);
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@moqhq0@doBatchAttention`} type="primary"  disabled ={selectedRowKeys.length<=0} onClick={this.batchAttention}>{getLabel(503955, '批量关注')}</Button>);
    // btns.push(
    //   <ButtonSelect
    //     datas={datas}
    //     btnProps={{ disabled: selectedRowKeys.length <= 0 }}
    //     dropdownProps={{ trigger: ['click'] }}
    //     dropBtnProps={{ title: getLabel(384039, "点击切换批量操作") }}
    //     btnOnClick={key => {
    //       if (key === 'batchForward') {
    //         this.doForward()
    //       } else if (key === 'batchAttention') {
    //         this.doAttention()
    //       }
    //     }}
    //     menuOnClick={(key, e) => attentionStore.clickButttonDrop(key)}
    //   />
    // );
    return btns;
  }
  doAttention = () => {
    const { attentionStore } = this.props;
    const { tableStore } = attentionStore;
    const selectedRowKeys = tableStore.selectedRowKeys;
    if(selectedRowKeys.length<=0)return;
    let idarr = selectedRowKeys.map(v => {
      const arr = v.split("_");
      const requestid = arr[0];
      return requestid;
    });
    let requestIds = idarr.join(",");
    allStore.wfFollowTypeSettingStore.isSingle = false
    allStore.wfFollowTypeSettingStore.followTypeSelectShow = true
    allStore.wfFollowTypeSettingStore.FollowRequestid = requestIds
  }
  doForward =()=>{
    const { attentionStore } = this.props;
    const { tableStore } = attentionStore;
    const selectedRowKeys = tableStore.selectedRowKeys;
    let title='';
    let msgList = [];
    selectedRowKeys.map(val=>{
      tableStore.datas.map(v=>{
            if(v.requestid==val){
                title = v.requestname
            }
        })
        msgList.push(
            {
              sharetitle: title,
              desc: title,
              linkurl: "/main/workflow/req?requestid="+val+"&isovertime=0&_workflowid=2&_workflowtype=2",
              linkurl_pc: "/main/workflow/req?requestid="+val+"&isovertime=0&_workflowid=2&_workflowtype=2",
              canforward: 1,
              callbackurl: "",
              sharetypename: "流程",
              showimage: "/images/p.png",
              sharetype: "workflow",
              shareid: val+""
            }
        )
    })
    let shareParams = {
        "resourcetype": 152,
        "resourceid": selectedRowKeys.join(','),
    }
    this.setState({msgList,shareParams},()=>{
        this.setState({visible:true})
    })
  }
  rightMenuSearch = () => {
    this.props.attentionStore.getSessionkey(); 
  }
  //右键菜单方法
  getRightMenu() {
    const { attentionStore, location } = this.props;
    const { tableStore, form } = attentionStore;
    const selectedRowKeys = tableStore.selectedRowKeys;
    const selectedLen = tableStore.selectedRowKeys.length;
    const formParams = form.getFormParams();
    let btns = [];

    btns.push({
      key: "search",
      icon: <i className='icon-workflow-Right-menu--search' />,
      content: getLabel(197, '搜索'),
      onClick: this.rightMenuSearch
    });
    
    btns.push({
      key: "setting",
      icon: <i className= 'icon-coms-Flow-setting' />,
      content: getLabel(503952, '关注类型设置'),
      onClick:this.typeSetting
    });

    btns.push({
      key: "batchHandle",
      icon: <i className='icon-coms-Subscribe'/>,
      content: getLabel('503955','批量关注'),
      disabled: selectedLen <= 0,
      onClick: this.batchAttention
    });
    btns.push({
      key: "colSet",
      icon: <i className='icon-coms-Custom' />,
      content: getLabel(32535, '显示列定制'),
      onClick: this.columnSetting
    });
    return btns;
  }

  columnSetting = () => {
    const { attentionStore: {tableStore } } = this.props;
      tableStore.setColSetVisible(true);
      tableStore.tableColSet(true);
  }

}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@1ygbpm`} msg={props.error ? props.error : getLabel(383324, '对不起，该页面异常，请联系管理员！')} />,
  { error: "" }
)(Attention);
